<?php


namespace app\service\model;


use app\service\Y;

class BannerImagesModel extends BaseModel
{

    protected $table = 'banner_images';

    protected $append = ['big_image', 'min_image'];

    /**
     * 管理banner位
     * @return \think\model\relation\BelongsTo
     */
    public function seat(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(BannerSeatModel::class, 'banner_seat_id', 'id');
    }

    /**
     * 小缩略图
     * @param $value
     * @param $data
     * @return array|string|string[]
     */
    public function getMinImageAttr($value, $data) {
        if ($data['image']) {
            return str_replace('.jpg', '-min.jpg', $data['image']);
        }
        return '';
    }

    /**
     * 大缩略图
     * @param $value
     * @param $data
     * @return array|string|string[]
     */
    public function getBigImageAttr($value, $data) {
        if ($data['image']) {
            return str_replace('.jpg', '-big.jpg', $data['image']);
        }
        return '';
    }

    /**
     * 保存数据
     * @param $param
     * @param $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function saveData($param, $id): \think\response\Json
    {
        $old_image = '';
        if ($id > 0) {
            $data = self::find($id);
            if (!$data) {
                return Y::error('参数错误');
            }
            $old_image = $data->image != $param['image'] ? $data->image : '';
        } else {
            $data = new self();
        }
        // 将图片从零时目录转入正式目录
        $param['image'] = event('image_storage', ['image' => $param['image'], 'type' => 'banner'], 'true');
        $data->save($param);
        unlink_old_image($old_image);
        return Y::success([], '保存成功');
    }

}